package yawning.mew.util;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class Json implements Iterable<Json> {
    /* package */ Object mObject;
    
    public Json(String s) {
        mObject = (Object)JSONValue.parse(s);
    }
    
    public Json(Object o) {
        mObject = o;
    }
    
    public Json get(int index) {
    	JSONArray array = (JSONArray)mObject;
    	if (index >= array.size()) return null;
    	Object obj = array.get(index);
        if (obj == null) return null;
        else return new Json(obj);
    }
    
    public Json get(String key) {
    	JSONObject obj = (JSONObject)mObject;
    	if (obj.containsKey(key)) {
    		Object o = obj.get(key);
    		if (o == null) return null;
    		else return new Json(o);
    	}
    	else return null;
    }
    
    public int intValue() {
        return ((Number)mObject).intValue();
    }
    
    public Set<Map.Entry<String,Json>> entrySet() {
        JSONObject obj = (JSONObject)mObject;
        Set<Map.Entry<String,Json>> s = new HashSet<Map.Entry<String,Json>>();
        @SuppressWarnings("unchecked") Set<Map.Entry<Object,Object>> set = obj.entrySet();
        for (Map.Entry<Object,Object> entry : set) {
            s.add(new Entry(entry));
        }
        return s;
    }
    
    private class Entry implements Map.Entry<String,Json> {
        Map.Entry<Object,Object> mEntry;
        
        Entry(Map.Entry<Object,Object> e) {
            mEntry = e;
        }
        
        @Override
        public String getKey() {
            return mEntry.getKey().toString();
        }

        @Override
        public Json getValue() {
            return new Json(mEntry.getValue());
        }

        @Override
        public Json setValue(Json value) {
            return new Json(mEntry.setValue(value.mObject));
        }
        
    }
    
    @Override
    public String toString() {
    	if (mObject == null) return null;
        return mObject.toString();
    }

    @Override
    public Iterator<Json> iterator() {
        return new It();
    }
    
    private class It implements Iterator<Json> {
        @SuppressWarnings("unchecked")
        Iterator<Object> mIterator = ((Iterable<Object>)mObject).iterator();
        
        @Override
        public boolean hasNext() {
            return mIterator.hasNext();
        }

        @Override
        public Json next() {
        	Object obj = mIterator.next();
        	if (obj != null) return new Json(obj);
        	else return null;
        }

        @Override
        public void remove() {
            mIterator.remove();
        }
    }
}
